<template>
  <div class="home bg-fff">
    <div class="topWrap">
      <img class="topBg" src="https://image.srea.org.cn/xcx/kaipan-rili-top-bg.jpg" alt="" srcset="">
      <!-- <div class="titWrap col-fff">
        <div class="title">开盘日历</div>
        <div class="subTit">信息仅供参考</div>
        <div class="subTit">实际信息请以开发商公布为准</div>
      </div> -->
    </div>
    <div id="capture">
      <div class="nav" id="topNav">
        <div class="navUl" id="topNavUl">
          <div class="navItem" ref="navBox" v-for="(item,index) in navs" :key="index">
            <div class="btnBox flex" :class="nowDate.getMonth()+1 == item.month?'active':''" @click="changeMonth(item,index,$event)">
              <span class="year col-fff">{{item.year}}</span>
              <span class="btn flex font13">{{item.month}}</span>
            </div>
          </div>
        </div>
      </div>
      <div class="monthTag"><span class="fontBold font20 font-PF-bold">{{nowDate.getMonth()+1}}</span>月·<span class="fontBold font-PF-bold">{{monthEngList[nowDate.getMonth()]}}</span> 开盘日历</div>
      <el-calendar v-model="nowDate">
        <template
          slot="dateCell"
          slot-scope="{data}">
          <div class="dayBody">
            <p class="day fontBold" :class="data.isSelected ? 'is-selected' : ''">
              {{ data.day.split('-').slice(2).join('') }}
            </p>
            <div>
              <div v-for="(item,index) in list" :key="index">
                <div v-if="item.day == data.day.split('-').slice(2).join('')">
                  <div v-if="item.chou.length > 0">
                    <div class="houseBody RCSty">
                      <p class="type fontBold font12">{{cityCode == '310100' ? '认购':'登记'}}</p>
                      <div class="houseItem font11 flex" v-for="(hos, num) in item.chou" :key="num" @click="toXCXHouse(hos)">
                        {{hos.title}}
                      </div>
                    </div>
                  </div>
                  <div v-if="item.pan.length > 0">
                    <div class="houseBody KAISty">
                      <p class="type fontBold font12">开盘</p>
                      <div class="houseItem font11 flex" v-for="(hos, num) in item.pan" :key="num" @click="toXCXHouse(hos)">
                        {{hos.title}}
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </template>
      </el-calendar>
    </div>
  </div>
</template>

<script>
// @ is an alias to /src
import wx from 'weixin-js-sdk';
import { initWXSDK, getCalendarAPI } from '@/api/api';
import { getHashValue, dataURLtoFile } from '@/common/common';
import { setToken, getToken } from '@/utils/auth';

export default {
  name: 'CalendarKai',
  data(){
    return {
      nowDate: new Date(),
      currMonth: new Date().getMonth()+1,
      monthEngList: ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Spt","Oct","Nov","Dec"],
      list: [],
      token: "",
      cityCode: '',
      navs: [],
      navScroll: null,
      platform: ''
    }
  },

  mounted(){
    // let token = getHashValue('token') || 'b2e89d7ed42da3a128e2ea47c882df8c8310e8ca';//debug:false
    // let token = getHashValue('token') || 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE3MzQ2MDI1ODgsImlhdCI6MTczMzk5Nzc4OCwiaXNzIjoiIiwiZGF0YSI6eyJ1c2VyX2lkIjoyfX0.Vn2AgKo42q0txcvpEPtu7IvbPjwI2zFXTey2TINTwxc';//debug:true
    let token = getHashValue('token');
    this.token = token;
    setToken(token);
    this.$store.commit('setToken', token);
    this.cityCode = getHashValue('cityCode') || '310100';
    this.platform = getHashValue('platform') || '';
    this.init();
  },
  methods:{
    //请求日历数据
    async requestData(info){
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0)'
      });
      await getCalendarAPI(info).then(res => {
        let {data } = res.detail;
        this.list = data;
        loading.close();
      })
    },

    //初始化
    init(){
      let nowMonthBefore = this.currMonth;
      let nowYearBefore = this.nowDate.getFullYear();
      let nowMonthAfter = this.currMonth;
      let nowYearAfter = this.nowDate.getFullYear();
      let dateArr = [{
        year: nowYearBefore,
        month: nowMonthBefore
      }];
      for(let i=0;i<6;i++) {
        nowMonthBefore = nowMonthBefore-1;
        if(nowMonthBefore <= 0) {
          nowYearBefore = nowYearBefore-1;
          nowMonthBefore = nowMonthBefore+12;
        }
        dateArr.unshift({
          year: nowYearBefore,
          month: nowMonthBefore
        })
      }
      for(let i=0;i<5;i++) {
        nowMonthAfter = nowMonthAfter+1;
        if(nowMonthAfter > 12) {
          nowYearAfter = nowYearAfter+1;
          nowMonthAfter = nowMonthAfter-12;
        }
        dateArr.push({
          year: nowYearAfter,
          month: nowMonthAfter
        })
      }

      this.navs = dateArr;

      //请求日历数据
      this.requestData({
        city: this.cityCode,
        year: this.nowDate.getFullYear(),
        month: this.currMonth
      })
      
      let url = window.location.href;
      // let url = location.href.split("#")[0];
      initWXSDK(url).then(res => {
        let details = res.detail;
        wx.config({
          debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
          appId: details.appId, // 必填，公众号的唯一标识
          timestamp: details.timestamp, // 必填，生成签名的时间戳
          nonceStr: details.nonceStr, // 必填，生成签名的随机串
          signature: details.signature, // 必填，签名
          jsApiList: [], // 必填，需要使用的JS接口列表
        });
        wx.ready(function() {
        });
        wx.error(function(err) {
        })
      })
      
      //导航栏居中
      let that = this;
      this.$nextTick(() => {
        let ul = document.querySelector('#topNavUl');
        let nav = document.getElementById("topNav");
        let window_offsetWidth = window.innerWidth; 
        let navItem = that.$refs.navBox[nowMonthBefore];
        let domoffsetWidth = navItem.offsetLeft,
          //中间值 =( 屏幕宽度 - li宽度 ) / 2;
          diffWidth = (window_offsetWidth - navItem.offsetWidth) / 2,
          //目标值 = offset - 中间值
          targetOffset = -(domoffsetWidth - diffWidth);
        let ul_width = ul.getBoundingClientRect().width;//开始
        
        // 未超出中间值
        if (-targetOffset < 0) {
          nav.scrollLeft = 0;
          return;
        }
        //末尾
        if(targetOffset <  window_offsetWidth - ul_width ){
          nav.scrollLeft = -(window_offsetWidth - ul_width);
          return;
        }       
        //正常
        nav.scrollLeft = -targetOffset
      })
    },

    //切换月份
    changeMonth(item, index, e){
      this.nowDate = new Date(Date.UTC(item.year, item.month-1));
      this.requestData({
        city: this.cityCode,
        year: item.year,
        month: item.month
      })
      let destination = index - 2;
      destination = destination < 0 ? 1 : destination;

      // 横向滑动居中
      let ul = document.querySelector('#topNavUl');
      let nav = document.getElementById("topNav");
      let window_offsetWidth = window.innerWidth; //屏幕宽度;
      let dom = e.target;
      if (dom) {
        let domoffsetWidth = dom.offsetLeft,
          //中间值 =( 屏幕宽度 - li宽度 ) / 2;
          diffWidth = (window_offsetWidth - dom.offsetWidth) / 2,
          //目标值 = offset - 中间值
          targetOffset = -(domoffsetWidth - diffWidth);
        let ul_width = ul.getBoundingClientRect().width;//开始
        
        // 未超出中间值
        if (-targetOffset < 0) {
          nav.scrollLeft = 0;
          return;
        }
        //末尾
        if(targetOffset <  window_offsetWidth - ul_width ){
          nav.scrollLeft = -(window_offsetWidth - ul_width);
          return;
        }       
        //正常
        nav.scrollLeft = -targetOffset
      }
    },

    //跳转小程序
    toXCXHouse(info){
      let time = new Date().getTime();
      let url = info.change 
        ? `/pages/product/dynamic/index?pageType=dynamic&productId=${info.id}&t_=${time}`
        : `/pages/product/detail/index?productId=${info.id}&t_=${time}`;
      var ua = window.navigator.userAgent.toLowerCase();
      //先判断是否微信浏览器
      if (ua.match(/MicroMessenger/i) == "micromessenger") {
        //再判断一下是否在小程序里
        wx.miniProgram.getEnv((res) => {
          if (res.miniprogram) {
            wx.miniProgram.navigateTo({
              url,
              success: function(){},
              fail: function(){}
            });
          }
        });
      }
    }
  }
}
</script>
<style scoped lang="less">
.home{
  min-height: 100vh;
  .topWrap{
    position: relative;
    .topBg{
      width: 100%;
    }
    .titWrap{
      position: absolute;
      top: 40px;
      left: 20px;
      .title{
        font-size: 25px;
        margin-bottom: 10px;
      }
      .subTit{
        font-size: 12px;
        margin-top: 6px;
      }
    }
  }
  .nav{
    display: flex;
    white-space: nowrap;
    margin-top: 10px;
    overflow-x: scroll;
    scrollbar-width: none;
    .navUl{
      display: inline-block;
      white-space: nowrap;
    }
    &::-webkit-scrollbar{
      display: none;
    }
    .navItem{
      text-align: center;
      width: 45px;
      display: inline-block;
      .btnBox{
        flex-direction: column;
        .year{
          font-size: 10px;
        }
        .btn{
          margin-top: 5px;
          width: 30px;
          height: 30px;
          border-radius: 50%;
        }
      }
      .active{
        .year{
          color: #333;
        }
        .btn{
          color: #fff;
          background-color: #007235;
        }
      }
    }
  }
  .monthTag{
    margin: 20px 15px 0px 15px;
  }
  .dayBody{
    text-align: center;
    margin: 0;
    padding: 0;
    .day{
      color: #333;
      padding: 5px 0px;
      border-top: 1px solid #EBEEF5;
      border-bottom: 1px solid #EBEEF5;
    }
    .houseBody{
      color: #333;
      margin: 10px 1px;
      border-radius: 4px;
      overflow: hidden;
      .type{
        color: #C0C4CC;
        height: 18px;
        line-height: 18px;
      }
    }
    .RCSty{
      background: rgba(185, 223, 207, 0.18);
      .type{
        color: #333;
        background-color: rgba(185, 223, 207, 1);
      }
      .houseItem{
        line-height: 1.3;
        padding: 5px 0px;
        &:last-child{
          border: none;
        }
      }
    }
    .KAISty{
      background: rgba(251, 237, 197, .2);
      .type{
        color: #333;
        background-color: rgba(251, 237, 197, 1);
      }
      .houseItem{
        line-height: 1.3;
        padding: 5px 0px;
        &:last-child{
          border: none;
        }
      }
    }
  }
}

</style>